<?php
ini_set( display_errors , TRUE);
	require_once __DIR__.'/ErrorCode.php';
	/**
	 * Class User
	 */
	class User
	{
		private $db;

		/**
		 * User constructor.
		 *
		 * @param $db
		 */
		public function __construct ( $db )
		{
			$this -> db = $db;
		}


		/**
		 * @param $username
		 * @param $password
		 */
		public function login($username, $password)
		{
			if (empty( $username)){
				throw new Exception('用户名不能为空',ErrorCode::USERNAME_CANNOT_EMPTY );
			}

			if (empty( $password)){
				throw new Exception('密码不能为空', ErrorCode::PASSWORD_CANNOT_EMPTY);
			}
			$sql = 'SELECT * FROM `user` WHERE  `username`=:username AND `password`=:password';
			$password = $this->_md5( $password);
			$stmt = $this->db->prepare($sql);
			$stmt->bindParam(':username', $username);
			$stmt->bindParam(':password', $password);
			$stmt->execute();
			$user = $stmt->fetch(PDO::FETCH_ASSOC);
			if (empty( $user)){
				throw new Exception('用户名或密码错误', ErrorCode::USERNAME_OR_PASSWORD_INVALID);
			}

		}

		/**
		 * @param $username
		 * @param $password
		 */
		public function register($username, $password)
		{
		if (empty( $username)){
			throw new Exception('用户名不能为空',ErrorCode::USERNAME_CANNOT_EMPTY );
		}

		if (empty( $password)){
			throw new Exception('密码不能为空', ErrorCode::PASSWORD_CANNOT_EMPTY);
		}
			if ( $this->isUserNameExists( $username)){
				throw new Exception('用户名已存在', ErrorCode::USERNAME_EXISTS);
			}
			//写入数据库
			$sql = 'INSERT INTO `user`(`username`, `password`, `created_at`)VALUE 
			(:username, :password, :created_at)';
			$created_at = time();
			$password = $this->_md5( $password);
			$stmt = $this->db->prepare($sql);
			$stmt->bindParam(':username', $username);
			$stmt->bindParam(':password', $password);
			$stmt->bindParam(':created_at', $created_at);
			if (!$stmt->execute()){
				throw new Exception('用户注册失败', ErrorCode::REGISTER_FAIL);
			}
			return [
				`userId` => $this->db->lastInsertId(),
				`username` => $username,
			    `created_at` => $created_at,
			];




		}



		private function _md5($string, $key = 'jiadianyan')
		{
			return md5( $string . $key);
		}

		private function isUserNameExists($username){
			$sql = 'SELECT * FROM `user` WHERE `username` =:username ';
			$stmt = $this->db->prepare($sql);
			$stmt->bindParam(':username', $username);
			$stmt->execute();
			$result = $stmt->fetch(PDO::FETCH_ASSOC);
			return !empty( $result);
		}
	}